//
//  DataAnalysisViewController.swift
//  SitPosition
//
//  Created by apple on 2019/1/27.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import UIKit
import Cartography
import Toast_Swift


class DataAnalysisViewController : GKNavigationBarViewController {
    
    // MARK: - Properties
    
    // 标题
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.Color.primaryDarkTextColor
        label.font = Theme.Font.boldFont(ofSize: 26)
        label.numberOfLines = 1
        label.lineBreakMode = .byTruncatingTail
        label.text = Strings.dataStat
        return label
    }()
    
    // 日期选择按钮
    lazy var dateFormatter: DateFormatter = {
        let tf: DateFormatter = DateFormatter()
        tf.dateFormat = "yyyy.MM.dd"
        return tf
    }()
    lazy var datePickerBtn: UIButton = {
        let value: String = dateFormatter.string(from: Date())
        let btn = UIButton(type: UIButton.ButtonType.custom)
        btn.contentHorizontalAlignment = .left
        btn.setImage(UIImage(named: "time_more"), for: UIControl.State.normal)
        btn.setTitle(value, for: UIControl.State.normal)
        btn.titleLabel?.font = Theme.Font.boldFont(ofSize: 16)
        btn.setTitleColor(Theme.Color.primaryDarkTextColor, for: UIControl.State.normal)
        btn.addTarget(self, action: #selector(_showDatePicker), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    // 图表
    lazy var chartView: PieGraphView = PieGraphView()
    lazy var chartTitleLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.Color.primaryDarkTextColor
        label.font = Theme.Font.regularFont(ofSize: 14)
        label.textAlignment = .center
        label.numberOfLines = 1
        label.text = Strings.dataStatStudyDuration
        return label
    }()
    
    lazy var chartSubtitleLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.Color.primaryDarkTextColor
        label.font = Theme.Font.boldFont(ofSize: 29)
        label.textAlignment = .center
        label.numberOfLines = 1
        return label
    }()
    
    lazy var chartTitleContainer: UIView = {
        let stackView = UIStackView(arrangedSubviews: [chartTitleLabel, chartSubtitleLabel])
        stackView.axis = .vertical
        stackView.distribution = .fill
        stackView.alignment = .center
        stackView.spacing = 17
        return stackView
    }()
    
    // 图表说明
    lazy var chartNoteView: UIView = {
        func coloredView(_ title: String, _ color: UIColor?) -> UIView {
            // 圆圈标记
            let circleWH: CGFloat = 13;
            let circle: UIView = UIView()
            circle.layer.cornerRadius = circleWH/2
            circle.layer.masksToBounds = true
            circle.backgroundColor = color
            

            // 标题
            let label: UILabel = UILabel()
            label.textColor = Theme.Color.primaryDarkTextColor
            label.font = Theme.Font.regularFont(ofSize: 14)
            label.numberOfLines = 1
            label.text = title
            label.lineBreakMode = .byTruncatingTail

            let stackView = UIStackView(arrangedSubviews: [circle, label])
            stackView.axis = .horizontal
            stackView.alignment = .center
            stackView.distribution = .fill
            stackView.spacing = 15
            
            // 设置约束
            constrain(circle) { v in
                v.width == circleWH
                v.height == circleWH
            }
            
            return stackView
        }
        let dataStatTypes: [DataStatType] = [
            DataStatType.ok,
            DataStatType.headSlant,
            DataStatType.bodySlantL,
            DataStatType.bodySlantR,
            DataStatType.headSlantLow,
            // DataStatType.headSlantRotate,
            DataStatType.unknownSlant
        ]
        let views: [UIView] = dataStatTypes.map { (t) in
            return coloredView(t.description, t.flagColor)
        }
        let stackView = UIStackView(arrangedSubviews: views)
        stackView.axis = .vertical
        stackView.alignment = .leading
        stackView.distribution = .fillEqually
        stackView.spacing = 19
        return stackView
    }()
    
    // 数据列表
    lazy var dataTableView: UITableView = {
        let tv = UITableView(frame: CGRect.zero, style: UITableView.Style.plain)
        tv.dataSource = self
        tv.delegate = self
        tv.rowHeight = 50
        tv.separatorStyle = .singleLine
        tv.separatorColor = Theme.Color.seperatorColor
        tv.separatorInset = UIEdgeInsets(top: 0, left: 35, bottom: 0, right: 35)
        tv.tableFooterView = UIView()
        tv.register(DataStatItemCell.self, forCellReuseIdentifier: DataStatItemCell.reusedIdentifier)
        return tv
    }()
    
    // 数据表
    var statDatetime: Date = Date() {
        didSet {
            _refreshData()
        }
    }
    var dataSource: [DataStatItem] = [] {
        didSet {
            let kRadius: CGFloat = 100
            var arcs: [PieArc] = []
            var startAngle: CGFloat = 0
            var endAngle: CGFloat = 0
            
            let percent: Float = dataSource.reduce(0) { (r, item) -> Float in
                return r+item.percent
            }
            
            if (dataSource.isEmpty || percent < Float.ulpOfOne) {
                endAngle = 360.0
                let arc = PieArc(radius: kRadius,
                                 startAngle: startAngle,
                                 endAngle: endAngle,
                                 color: Theme.Color.primaryBackgroundColor)
                arcs.append(arc)
            } else {
                for item in dataSource {
                    endAngle = startAngle + CGFloat((item.percent/100.0)*360.0)
                    let arc = PieArc(radius: kRadius,
                                     startAngle: startAngle,
                                     endAngle: endAngle,
                                     color: item.type.flagColor ?? UIColor.black)
                    arcs.append(arc)
                    startAngle = endAngle
                }
            }
            chartView.arcs = arcs
        }
    }
    var totalLearningDuration: TimeInterval = 0 {
        didSet {
            chartSubtitleLabel.text = totalLearningDuration.formatedTimeString
        }
    }
    
    // MARK: - Object lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        // 导航栏
        gk_navBackgroundColor = UIColor.clear
        gk_navLeftBarButtonItem = UIBarButtonItem(imageName: "ic_nav_back_black", target: self, action: #selector(_backButtonTapped))
        
        // 视图
        view.addSubviews([
            titleLabel,
            datePickerBtn,
            chartView,
            chartTitleContainer,
            chartNoteView,
            dataTableView
            ])
        _setupContraints()
        
        // 设置日期选择按钮的标题、ICON对齐方式
        datePickerBtn.setTitleAlign(with: UIButton.TitleAlignType.left, margin: 10)
        
        // 拉取数据
        let kRadius: CGFloat = 100
        chartView.arcs = [
            PieArc(radius: kRadius, startAngle: 0, endAngle: 360, color: UIColor.lightGray)
        ]
        _refreshData()
    }
    
    // 拉取数据
    // @isMore：YES - 下拉刷新数据；NO - 上拉加载更多
    func _fetchData(_ completion: @escaping (_ error: Error?) -> ()) {
        let tiInSeconds: TimeInterval = statDatetime.timeIntervalSince1970
        let tiInMillseconds: Int64 = Int64(tiInSeconds) * 1000
        NetworkClient.instance.statByDate(statisticDate: tiInMillseconds, success: { [weak self] (data) in
            // 检查参数
            guard let data_ = data else {
                completion(SPError.unexpectedServerResponse)
                return
            }
            // 注册成功
            do {
                let decoder: JSONDecoder = JSONDecoder()
                let dsc = try decoder.decode(DataStatCollection.self, from: data_)
                self?.totalLearningDuration = dsc.learningDuration()
                self?.dataSource = dsc.bridge2DataStatItem() ?? []
                completion(nil)
            } catch {
                completion(error)
            }
        }, failure: completion)
    }
    
    func _refreshData() {
        view.makeToastActivity(ToastPosition.center)
        
        let value: String = dateFormatter.string(from: statDatetime)
        datePickerBtn.setTitle(value, for: UIControl.State.normal)
        
        _fetchData { [weak self] (error) in
            defer {
                self?.view.hideToastActivity()
                self?.dataTableView.reloadData()
            }
            guard let error_ = error else {
                return
            }
            self?.view.makeToast(error_.networkErrorMessage ?? Strings.networkError)
        }
    }
}

// MARK: - UITableViewDataSource / UITableViewDelegate

extension DataAnalysisViewController : UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: DataStatItemCell.reusedIdentifier,
                                                 for: indexPath) as! DataStatItemCell
        cell.selectionStyle = .none
        cell.data = dataSource[indexPath.row]
        return cell
    }
}

// MARK: - Private Methods

extension DataAnalysisViewController {
    
    // 设置视图约束
    func _setupContraints() {
        
        // titleLabel
        constrain(titleLabel, gk_navigationBar, view) { v, sibling, parent in
            v.top == sibling.bottom + 10
            v.left == parent.left + 15
            v.width == 110
            v.height == 25
        }
        
        // datePickerBtn
        constrain(datePickerBtn, titleLabel, view) { v, sibling, parent in
            v.top == sibling.bottom + 20
            v.left == sibling.left
            v.right == sibling.right
            v.height == 20
        }
        
        // chartView
        constrain(chartView, datePickerBtn, view) { v, sibling, parent in
            v.top == sibling.bottom + 20
            v.left == sibling.left + 15
            v.width == 200
            v.height == 200
        }
        
        // chartTitleLabel
        constrain(chartTitleContainer, chartView, view) { v, sibling, parent in
            v.centerX == sibling.centerX
            v.centerY == sibling.centerY
        }
        
        // chartNoteView
        constrain(chartNoteView, chartView, view) { v, sibling, parent in
            v.centerY == sibling.centerY
            v.left == sibling.right + 30
            v.right == parent.right - 15
            v.height <= sibling.height ~ UILayoutPriority.defaultLow
        }
        
        // dataTableView
        constrain(dataTableView, chartView, view) { v, sibling, parent in
            v.top == sibling.bottom + 30
            v.left == parent.left
            v.right == parent.right
            v.bottom == parent.bottom
        }
    }
    
    // 显示日期选择器
    @objc func _showDatePicker() {
        // 显示日期选择器
        let picker = DatePickerController()
        picker.onGotValue = { [weak self] value in
            self?.statDatetime = value ?? Date()
            self?.dismiss(animated: true, completion: nil)
        }
        picker.modalPresentationStyle = .overCurrentContext
        picker.modalTransitionStyle = .crossDissolve
        present(picker, animated: true, completion: nil)
    }
    
    // 返回按钮点击事件
    @objc func _backButtonTapped() {
        if presentingViewController != nil {
            dismiss(animated: true, completion: nil)
        } else {
            navigationController?.popViewController(animated: true)
        }
    }
}
